package com.rain.shoppingscienceproj.ui.activity.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.rain.shoppingscienceproj.R;
import com.rain.shoppingscienceproj.http.BaseSubscriber;
import com.rain.shoppingscienceproj.http.ExceptionHandle;
import com.rain.shoppingscienceproj.http.RetrofitClient;
import com.rain.shoppingscienceproj.module.Address;
import com.rain.shoppingscienceproj.module.CarData;
import com.rain.shoppingscienceproj.module.ShoppingcarDto;
import com.rain.shoppingscienceproj.module.SubAddress;
import com.rain.shoppingscienceproj.module.SubGoods;
import com.rain.shoppingscienceproj.ui.activity.BaseActivity;
import com.rain.shoppingscienceproj.ui.activity.address.AddressActivity;
import com.rain.shoppingscienceproj.ui.activity.address.ShowAddressActivity;
import com.rain.shoppingscienceproj.ui.activity.pay.PayActivity;
import com.rain.shoppingscienceproj.ui.adapter.MakeOrderAdapter;
import com.rain.shoppingscienceproj.ui.base.GlobalData;
import com.rain.shoppingscienceproj.ui.utile.DialogUtils;
import com.rain.shoppingscienceproj.ui.utile.TitleUtils;
import com.rain.shoppingscienceproj.utils.AppManager;
import com.rain.shoppingscienceproj.utils.LoadingDialog;
import com.rain.shoppingscienceproj.utils.layoutmanager.CustomLinearLayoutManager;
import com.rain.shoppingscienceproj.utils.toast.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.ResponseBody;


public class MakeOrderActivity extends BaseActivity {


    @BindView(R.id.rv_data)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_address_mobile)
    TextView tv_address_mobile;
    @BindView(R.id.tv_address_name)
    TextView tv_address_name;
    @BindView(R.id.tv_add_address)
    TextView tv_add_address;
    @BindView(R.id.ll_address)
    LinearLayout ll_address;
    @BindView(R.id.tv_money)
    TextView tv_money;

    private ArrayList<CarData> carDataList;
    private int type;
    private Address addressData;
    double doubleGoodsMoney = 0.00;
    DecimalFormat df = new DecimalFormat("#.00");
    private boolean isAddress = false;
    private MakeOrderAdapter makeOrderAdapter;

    @OnClick(R.id.ll_address)
    void address() {
        Intent intent = new Intent(this, ShowAddressActivity.class);
        intent.putExtra("type", 1);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_make_order);
        AppManager.getAppManager().addActivity(this);
        ButterKnife.bind(this);
        TitleUtils.TitleView(this, "确认订单");
        type = getIntent().getIntExtra("type", 0);
        carDataList = (ArrayList<CarData>) getIntent().getSerializableExtra("carDataList");
        userInfo = GlobalData.getUserInfo();
        loadingDialog = new LoadingDialog(this, "正在加载...");
        initView();
        initData();
        initListener();
    }

    private void initView() {
        mRecyclerView.setLayoutManager(new CustomLinearLayoutManager(this));
        makeOrderAdapter = new MakeOrderAdapter(this, 6);
        mRecyclerView.setAdapter(makeOrderAdapter);
        makeOrderAdapter.setList(carDataList);
        double doubleMoney = 0.00;
        for (int i = 0; i < carDataList.size(); i++) {
            CarData carData = carDataList.get(i);
            for (int j = 0; j < carData.getList().size(); j++) {
                ShoppingcarDto goods = carData.getList().get(j);
                double kuaidi = 0;
                if (goods.getGoodsKtpay() != null || !goods.getGoodsKtpay().equals("")) {
                    kuaidi = Double.valueOf(goods.getGoodsKtpay()) / 100;
                }
                doubleMoney += (Double.valueOf(goods.getGoodsPay()) / 100) * goods.getSize() + kuaidi * goods.getSize();
            }
        }
        doubleGoodsMoney = doubleMoney;
        if (doubleMoney < 1) {
            tv_money.setText(0 + df.format(doubleMoney));
        } else {
            tv_money.setText(df.format(doubleMoney));
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (isAddress) {
            isAddress = false;
            initData();
        }
    }

    private void initData() {
        Map<String, String> map = new HashMap<>();
//        map.put("userId", userInfo.getUserId());
        map.put("token", userInfo.getToken());
        loadingDialog.show();
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .queryApproveAddress(map, new BaseSubscriber<Address>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
//                        ToastUtils.showShortToast(e.Message);
                        tv_add_address.setVisibility(View.VISIBLE);
                        ll_address.setVisibility(View.GONE);
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(Address address) {
                        super.onNext(address);
                        loadingDialog.dismiss();
                        tv_add_address.setVisibility(View.GONE);
                        ll_address.setVisibility(View.VISIBLE);
                        addressData = address;
                        setAddress(address);
                    }
                });

    }

    public void setAddress(Address address) {
        String addressStr = "";
        String[] stirs = address.getAddress().split("-");
        for (int i = 0; i < stirs.length; i++) {
            addressStr += stirs[i];
        }
        tv_address_mobile.setText("收货人 : " + address.getAddressName() + "\t\t\t\t\t\t\t\t\t " + address.getAddressPhone());
        tv_address_name.setText("收货地址 : " + addressStr + address.getAddressDetils());
    }

    private void initListener() {

    }

    @OnClick(R.id.tv_add_address)
    void AddAddress() {
        isAddress = true;
        Intent intent = new Intent(this, AddressActivity.class);
        intent.putExtra("isCheck", true);
        startActivity(intent);
    }

    @OnClick(R.id.tv_submit)
    void tv_submit() {
        if (addressData == null) {
            ToastUtils.showShortToast("请添加收货地址");
            return;
        }
        SubAddress subAddress = new SubAddress(addressData.getAddressName(), addressData.getAddressPhone(), addressData.getAddress() + addressData.getAddressDetils());
        if (type == 1) {
            oneGoods(subAddress);
        } else {
            listGoods(subAddress);
        }
    }

    private void listGoods(SubAddress subAddress) {
        loadingDialog.show();
        Map<String, String> map = new HashMap<>();
        Gson gson = new Gson();
        String addressJson = gson.toJson(subAddress);
        List<SubGoods> list = new ArrayList<>();
        for (CarData carData : carDataList) {
            for (ShoppingcarDto shopCar :
                    carData.getList()) {
                SubGoods subGoods = new SubGoods(shopCar.getShoppingcarId(), shopCar.getSize());
                list.add(subGoods);
            }
        }
        String shoppingCarArrayStr = gson.toJson(list);
        map.put("token", userInfo.getToken());
        map.put("shoppingCarArrayStr", shoppingCarArrayStr);
        map.put("addressStr", addressJson);
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .submitListOrder(map, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast("网络错误");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int status = json.getInt("code");
                            if (status == 0) {
                                JSONObject jsonObject = json.getJSONObject("data");
                                String orderId = jsonObject.getString("orderId");
                                String pay = jsonObject.getString("pay");
                                Intent intent = new Intent(MakeOrderActivity.this, PayActivity.class);
                                intent.putExtra("type", orderId);
                                intent.putExtra("id", pay);
                                intent.putExtra("status", 1);
                                startActivity(intent);
                                finish();
                            } else {
                                DialogUtils.dialogRegis(MakeOrderActivity.this, json.getString("message"));
                                DialogUtils.getTv_sure().setOnClickListener(view -> {
                                    DialogUtils.dismissDialog();
                                });
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

    private void oneGoods(SubAddress subAddress) {
        loadingDialog.show();
        Map<String, String> map = new HashMap<>();
        Gson gson = new Gson();
        String addressJson = gson.toJson(subAddress);
        map.put("token", userInfo.getToken());
        map.put("goodId", carDataList.get(0).getList().get(0).getGoodsId() + "");
        map.put("num", carDataList.get(0).getList().get(0).getSize() + "");
        map.put("addressStr", addressJson);
        RetrofitClient.getInstance(this)
                .createBaseApi()
                .submitOneOrder(map, new BaseSubscriber<ResponseBody>(this) {
                    @Override
                    public void onError(ExceptionHandle.ResponeThrowable e) {
                        ToastUtils.showShortToast("网络错误");
                        loadingDialog.dismiss();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        super.onNext(responseBody);
                        loadingDialog.dismiss();
                        try {
                            String request = responseBody.string();
                            JSONObject json = new JSONObject(request);
                            int status = json.getInt("code");
                            if (status == 0) {
                                JSONObject jsonObject = json.getJSONObject("data");
                                String orderId = jsonObject.getString("orderId");
                                String pay = jsonObject.getString("pay");
                                Intent intent = new Intent(MakeOrderActivity.this, PayActivity.class);
                                intent.putExtra("type", orderId);
                                intent.putExtra("id", pay);
                                intent.putExtra("status", 1);
                                startActivity(intent);
                                finish();
                            } else {
                                DialogUtils.dialogRegis(MakeOrderActivity.this, json.getString("message"));
                                DialogUtils.getTv_sure().setOnClickListener(view -> {
                                    DialogUtils.dismissDialog();
                                });
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case 1:
                if (data != null) {
                    addressData = (Address) data.getSerializableExtra("address");
                    setAddress(addressData);
                }
                break;
        }

    }

}
